/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cc.altius.dao.impl;

import cc.altius.dao.SmsDao;
import cc.altius.model.SmsDetails;
import cc.altius.model.SmsSituation;
import cc.altius.model.SmsTemplate;
import cc.altius.model.SmsType;
import cc.altius.utils.DateUtils;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.LogicalExpression;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author sagar
 */
@Repository("SmsDao")
public class SmsDaoImpl implements SmsDao {

    private HibernateTemplate hibernateTemplate;
    private SessionFactory sessionFactory;
    Session session;
    Query query;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
        this.hibernateTemplate = new HibernateTemplate(sessionFactory);
    }

    @Override
    @Transactional
    public int addSms(int customerId, int smsTypeId, String smsBody, String smsPhoneNos, int statusId, String response) {
        System.out.println("customerId :"+customerId);
        System.out.println("smsTypeId :"+smsTypeId);
        System.out.println("smsBody :"+smsBody);
        System.out.println("smsPhoneNos :"+smsPhoneNos);
        System.out.println("statusId :"+statusId);
        System.out.println("response :"+response);
        
        
        try {
            Date curDate = DateUtils.getCurrentDateObject(DateUtils.IST);
            session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
            SmsDetails smsDetails = new SmsDetails();
            //SmsType smsType = new SmsType();
            //smsType.setSmsTypeId(smsTypeId);
            //smsDetails.setSmsType(smsType);
            SmsTemplate smsTemplate = new SmsTemplate();
            smsTemplate.setSmsTemplateId(smsTypeId);
            smsDetails.setSmsTemplate(smsTemplate);
            smsDetails.setMessage(smsBody);
            smsDetails.setPhoneNo(smsPhoneNos);
            smsDetails.setCreatedDate(curDate);
            smsDetails.setLastAttemptedDate(curDate);
            smsDetails.setCustomerId(customerId);
            smsDetails.setSmsStatusId(statusId);
            smsDetails.setResponse(response);
            smsDetails.setAttempts(1);
            int smsId = (Integer) this.hibernateTemplate.save(smsDetails);
            return smsId;
        } catch (Exception e) {
            System.out.println("error :"+e.getMessage());
            e.printStackTrace();
            return 0;
        }


    }

    @Override
    @Transactional
    public List<SmsDetails> getFailedSmsList() {
        //System.out.println("inside getFailed LIst");
        try {
            session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
            Criteria cr = session.createCriteria(SmsDetails.class);
            Criterion smsStatusId1 = Restrictions.eq("smsStatusId", 0);
            Criterion smsStatusId2 = Restrictions.eq("smsStatusId", 2);
            Criterion attempts = Restrictions.lt("attempts", 3);
            LogicalExpression andExp = Restrictions.and(smsStatusId2, attempts);
            LogicalExpression orExp = Restrictions.or(andExp, smsStatusId1);
            cr.add(orExp);
            //System.out.println("cr.list()"+cr.list());
            return cr.list();
        } catch (Exception e) {
            e.printStackTrace();;
            return null;
        }
    }

    @Override
    @Transactional
    public List<SmsSituation> getSmsSituationList() {
        return this.hibernateTemplate.find("From SmsSituation ");
    }

    @Override
    @Transactional
    public List<SmsType> getSmsTypeList() {
        return this.hibernateTemplate.find("From SmsType ");
    }

    @Override
    @Transactional
    public int UpdateSms(SmsDetails sms) {
        Date curDate = DateUtils.getCurrentDateObject(DateUtils.IST);
        session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        try {
            String hql = "Update "
                    + " SmsDetails as sms"
                    + " set "
                    + " sms.smsStatusId=:smsStatusId,"
                    + " sms.response=:response,"
                    + " sms.lastAttemptedDate=:lastAttemptedDate,"
                    + " sms.attempts=:attempts"
                    + " WHERE sms.smsId=:smsId";
            query = session.createQuery(hql);
            query.setParameter("smsStatusId", sms.getSmsStatusId());
            query.setParameter("response", sms.getResponse());
            query.setParameter("lastAttemptedDate", curDate);
            query.setParameter("attempts", sms.getAttempts());
            query.setParameter("smsId", sms.getSmsId());
            int rowCount = query.executeUpdate();
            return rowCount;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

//    @Override
//    @Transactional
//    public SmsType SmsTypeName(int smsTypeId) {
//        
//        session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
//        String hql= "From SmsType AS smsType"
//                + " where smsTypeId=:smsTypeId";
//        query = session.createQuery(hql);
//        query.setParameter("smsTypeId",smsTypeId);
//        return (SmsType) query.uniqueResult();
//    }
    @Override
    @Transactional
    public SmsTemplate SmsTemplateName(int smsTemplateId) {
        session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        String hql = "From SmsTemplate AS smsTemplate "
                + "where smsTemplateId=:smsTemplateId";
        query = session.createQuery(hql);
        query.setParameter("smsTemplateId", smsTemplateId);
        return (SmsTemplate) query.uniqueResult();
    }

    @Override
    @Transactional
    public List<Map<String, Object>> reportSmsStatus(String startDate, String stopDate) {
        session = this.sessionFactory.getCurrentSession();
        query = session.createQuery(" select new map("
                + " count(*) as total,"
                + " (SUM(CASE WHEN sms.smsStatusId=1 THEN 1 ELSE 0 END)) as success,"
                + " (SUM(CASE WHEN sms.smsStatusId=2 and sms.attempts>=3 THEN 1 ELSE 0 END)) as failed,"
                + " (SUM(CASE WHEN sms.smsStatusId=2 and sms.attempts<3 THEN 1 else 0 END)) as Pending, "
                + " (SUM(CASE WHEN sms.smsStatusId=0 THEN 1 else 0 END)) as notsent) "
                + " from SmsDetails sms where sms.createdDate >='" + startDate + "' and sms.createdDate <='" + stopDate + "')");
        return query.list();
    }

    @Override
    @Transactional
    public List<SmsDetails> getFailedSmsListDateWise(String startDate, String stopDate) {
        return this.hibernateTemplate.find("from SmsDetails sms where sms.smsStatusId=2 and sms.attempts>=3 and sms.createdDate >='" + startDate + " 00:00:00' and sms.createdDate <='" + stopDate + " 23:59:59' ");
    }

    @Override
    @Transactional
    public void resendSmsViaButton(int smsId) {
        session = this.hibernateTemplate.getSessionFactory().getCurrentSession();
        try {
            String hql = "Update "
                    + " SmsDetails as sms"
                    + " set "
                    + " sms.attempts=:attempts"
                    + " WHERE sms.smsId=:smsId";
            query = session.createQuery(hql);
            query.setParameter("attempts", 0);
            query.setParameter("smsId", smsId);
            query.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public List<SmsDetails> getFailedSmsListForReport(String startDate, String stopDate) {
        if ("0".equals(startDate) && "0".equals(stopDate)) {
            startDate = DateUtils.getCurrentDateString(DateUtils.IST, DateUtils.YMD);
            return this.hibernateTemplate.find("from SmsDetails sms where sms.smsStatusId=2 and sms.attempts>=3 and sms.createdDate>='" + startDate + " 00:00:00' and sms.createdDate<='" + startDate + " 23:59:59' ");
        } else {
            return this.hibernateTemplate.find("from SmsDetails sms where sms.smsStatusId=2 and sms.attempts>=3 and sms.createdDate>='" + startDate + " 00:00:00' and sms.createdDate<='" + stopDate + " 23:59:59' ");
        }
    }

    @Override
    @Transactional
    public List<SmsDetails> getSuccessSmsListForReport(String startDate, String stopDate) {
        if ("0".equals(startDate) && "0".equals(stopDate)) {
            startDate = DateUtils.getCurrentDateString(DateUtils.IST, DateUtils.YMD);
            return this.hibernateTemplate.find("from SmsDetails sms where sms.smsStatusId=1 and sms.createdDate>='" + startDate + " 00:00:00' and sms.createdDate<='" + startDate + " 23:59:59' ");
        } else {
            return this.hibernateTemplate.find("from SmsDetails sms where sms.smsStatusId=1 and sms.createdDate>='" + startDate + " 00:00:00' and sms.createdDate<='" + stopDate + " 23:59:59' ");
        }
    }

    @Override
    @Transactional
    public List<SmsDetails> getPendingSmsListForReport(String startDate, String stopDate) {
        if ("0".equals(startDate) && "0".equals(stopDate)) {
            startDate = DateUtils.getCurrentDateString(DateUtils.IST, DateUtils.YMD);
            return this.hibernateTemplate.find("from SmsDetails sms where sms.smsStatusId=2 and sms.attempts<3 and sms.createdDate>='" + startDate + " 00:00:00' and sms.createdDate<='" + startDate + " 23:59:59' ");
        } else {
            return this.hibernateTemplate.find("from SmsDetails sms where sms.smsStatusId=2 and sms.attempts<3 and sms.createdDate>='" + startDate + " 00:00:00' and sms.createdDate<='" + stopDate + " 23:59:59' ");
        }
    }
}
